import { STORAGE_KEY_SEARCH_HISTORY } from '@/common/utils/constants';

export interface HistoryData {
  history?: string[];
}

const MAX_HISTORY_COUNT = 5;

export const getHistory = () => {
  const data: HistoryData = JSON.parse(localStorage.getItem(STORAGE_KEY_SEARCH_HISTORY) ?? '{}') || {};

  return data.history || [];
}

export const addHistory = (text: string) => {
  const data: HistoryData = JSON.parse(localStorage.getItem(STORAGE_KEY_SEARCH_HISTORY) ?? '{}') || {};

  data.history = data.history || [];

  if (!data.history.includes(text)) {
    data.history.push(text);
  }

  if (data.history.length > MAX_HISTORY_COUNT) {
    data.history.shift();
  }

  localStorage.setItem(STORAGE_KEY_SEARCH_HISTORY, JSON.stringify(data));

  return data.history;
}

export const clearHistory = () => {
  localStorage.removeItem(STORAGE_KEY_SEARCH_HISTORY);
}

export const setHistory = (history: string[]) => {
  localStorage.setItem(STORAGE_KEY_SEARCH_HISTORY, JSON.stringify({ history }));
}
